package com.ygqh.baby.service.impl;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.mapper.YgAgentInviteRecordMapper;
import com.ygqh.baby.model.AgentUserModel;
import com.ygqh.baby.model.YgUserRecommendModel;
import com.ygqh.baby.po.*;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.RC4Util;
import com.ygqh.baby.utils.ShareCodeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.crazycake.shiro.SerializeUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Ss
 */
@Service
public class YgAgentInviteRecordServiceImpl implements YgAgentInviteRecordService {
	
	private Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

	private final int every_month_count = 5; // 每月为一个代理生成邀请码的个数

	@Autowired
	private YgAgentInviteRecordMapper ygAgentInviteRecordMapper;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private ScheduleJobService scheduleJobService;
	@Autowired
	private WxMpMessageService wxMpMessageService;
	@Autowired
	private YgUserMemberService ygUserMemberService;
	@Autowired
	private YgAgentService ygAgentService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgUserBalanceDetailService ygUserBalanceDetailService;
	@Autowired
	private YgInformService ygInformService;

	@Override
	public List<YgAgentInviteRecord> find() {
		YgAgentInviteRecordExample example = new YgAgentInviteRecordExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygAgentInviteRecordMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		YgAgentInviteRecordExample example = new YgAgentInviteRecordExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return ygAgentInviteRecordMapper.countByExample(example);
	}

	@Override
	public YgAgentInviteRecord findById(Long id) {
		return ygAgentInviteRecordMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(YgAgentInviteRecord ygAgentInviteRecord) {
		return ygAgentInviteRecordMapper.insertSelective(ygAgentInviteRecord);
	}

	@Override
	public int update(YgAgentInviteRecord ygAgentInviteRecord) {
		return ygAgentInviteRecordMapper.updateByPrimaryKeySelective(ygAgentInviteRecord);
	}

	@Override
	public ResultSet<AgentUserModel> search(QueryInfo queryInfo, String nickName, String userName, Date startDate,
											Date endDate, Date orderStartDate, Date orderEndDate, Long levelId) {
		int total = ygAgentInviteRecordMapper.countSuper(nickName, userName, startDate, endDate, orderStartDate,
				orderEndDate, levelId);
		if (total == 0) {
			return new ResultSet<>();
		}
		List<AgentUserModel> result = ygAgentInviteRecordMapper.selectSuper(queryInfo, nickName, userName, startDate,
				endDate, orderStartDate, orderEndDate, levelId);
		return new ResultSet<>(total, result);
	}

	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		YgAgentInviteRecordExample example = new YgAgentInviteRecordExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		YgAgentInviteRecord record = new YgAgentInviteRecord();
		record.setStatus(DataStatus.Delete);
		return ygAgentInviteRecordMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[] { id });
	}

	@Override
	public int saveOrUpdate(YgAgentInviteRecord ygAgentInviteRecord) {
		int r = 0;
		if (ygAgentInviteRecord.getId() != null) {
			r = this.update(ygAgentInviteRecord);
		} else {
			r = this.save(ygAgentInviteRecord);
		}
		return r;
	}

	@Override
	public List<YgAgentInviteRecord> findByReceiveUserId(Long receiveUserId) {
		if (receiveUserId == null) {
			return new ArrayList<>();
		}
		YgAgentInviteRecordExample example = new YgAgentInviteRecordExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name()).andReceiveUserIdEqualTo(receiveUserId);
		example.setOrderByClause("receive_time DESC");
		return ygAgentInviteRecordMapper.selectByExample(example);
	}

	@Override
	public YgAgentInviteRecord findValidByReceiveUserId(Long receiveUserId) {
		if (receiveUserId == null) {
			return null;
		}
		List<YgAgentInviteRecord> recordList = this.findByReceiveUserId(receiveUserId);
		return CollectionUtils.isNotEmpty(recordList) ? recordList.get(0) : null;
	}

	@Override
	public YgAgentInviteRecord findByInviteCode(String inviteCode) {
		YgAgentInviteRecordExample example = new YgAgentInviteRecordExample();
		example.createCriteria().andInviteCodeEqualTo(inviteCode).andStatusEqualTo(DataStatus.Valid.name());
		List<YgAgentInviteRecord> list = ygAgentInviteRecordMapper.selectByExample(example);
		return CollectionUtils.isEmpty(list) ? null : list.get(0);
	}

	@Override
	public List<YgAgentInviteRecord> findByUserIdListAndBetweenTime(List<Long> userIdList, Date startDate, Date endDate) {
		return ygAgentInviteRecordMapper.selectByUserIdListAndBetweenTime(CollectionUtils.isEmpty(userIdList) ? null : userIdList, startDate, endDate);
	}

	@Override
	public int addBatch(List<YgAgentInviteRecord> recordList) {
		int row = 0;
		if (CollectionUtils.isEmpty(recordList)) {
			return row;
		}
		List<YgAgentInviteRecord> insertList = new ArrayList<>();
		for (int i = 0; i < recordList.size(); i++) {
			insertList.add(recordList.get(i));
			if (insertList.size() == 50 || i == recordList.size() - 1) {
				row += ygAgentInviteRecordMapper.insertBatch(insertList);
				insertList.clear();
			}
		}
		if (row > 0) {
			updateBatchWithInviteCode(recordList);
		}
		return row;
	}

	private int updateBatchWithInviteCode(List<YgAgentInviteRecord> recordList) {
		int row = 0;
		if (CollectionUtils.isEmpty(recordList)) {
			return row;
		}
		List<YgAgentInviteRecord> updateList = new ArrayList<>();
		for (int i = 0; i < recordList.size(); i++) {
			YgAgentInviteRecord record = recordList.get(i);
			String inviteCode = generateCode();
			updateList.add(new YgAgentInviteRecord(record.getId(), inviteCode));
			if (updateList.size() == 50 || i == recordList.size() - 1) {
				row += ygAgentInviteRecordMapper.updateBatch(updateList);
				updateList.clear();
			}
		}
		return row;
	}

	@SuppressWarnings("unchecked")
	private String generateCode() {
		byte[] bs = redisDao.get(RedisConstant.AGENT_INVITE_CODE.getBytes());
		List<String> codeList = null;
		if (bs == null || bs.length == 0) {
			List<YgAgentInviteRecord> list = this.find();
			if (CollectionUtils.isNotEmpty(list)) {
				codeList = list.stream().map(YgAgentInviteRecord::getInviteCode).collect(Collectors.toList());
			}
		} else {
			codeList = (List<String>) SerializeUtils.deserialize(bs);
		}
		String code = RC4Util.generateCode(codeList);
		redisDao.set(RedisConstant.AGENT_INVITE_CODE.getBytes(), SerializeUtils.serialize(codeList), 0);
		return code;
	}

	@Override
	public List<AgentUserModel> findReceiveListByUserId(Long userId) {
		return ygAgentInviteRecordMapper.selectReceiveListByUserId(userId);
	}

	@Override
	public List<YgAgentInviteRecord> findInviteCodeListByUserId(Long userId) {
		Date now = new Date();
		return this.findByUserIdListAndBetweenTime(Arrays.asList(userId), DateConvertUtils.getMonthStartDate(now),
				DateConvertUtils.getDateEnd(DateConvertUtils.getMonthEndDate(now)));
	}

	@Override
	public Message rechargeUserAgent(String inviteCode, Long userId) {
		if (StringUtils.isBlank(inviteCode)) {
			return Message.error("邀请码为空", inviteCode);
		}
		YgAgentInviteRecord inviteRecord = this.findByInviteCode(inviteCode);
		if (inviteRecord == null) {
			return Message.error("邀请码不存在", inviteCode);
		}
		if (inviteRecord.getReceiveUserId() != null) {
			return Message.error("该邀请码已被使用", inviteCode);
		}
		if (inviteRecord.getUserId().compareTo(userId) == 0) {
			return Message.error("不可使用自己的邀请码", inviteCode);
		}
		YgUser receiveUser = ygUserService.findById(userId);
		if (receiveUser.isUserAgent()) {
			return Message.error("您当前已经是代理", null);
		}
		YgAgentInviteRecord validByReceiveUserId = this.findValidByReceiveUserId(userId);
		if (validByReceiveUserId != null && validByReceiveUserId.getCancelTime().after(DateConvertUtils.addMonth(new Date(), -3))) {
			return Message.error("代理被取消三个月内，不可再被邀请", validByReceiveUserId);
		}
		Date now = new Date();
		Date expireTime = DateConvertUtils.getMonthEndDate(DateConvertUtils.addMonth(now, 1));
		int row = this.update(
				new YgAgentInviteRecord(inviteRecord.getId(), userId, receiveUser.getUserName(), now, InviteType.Ordinary, CheckStatus.Pass, expireTime));
		if (row > 0) {
			writeBackUserInfo(receiveUser); // 回写用户信息
			this.addBatch(generateInviteCode(receiveUser, every_month_count)); // 成为代理，生成邀请码
		}
		return Message.success(1);
	}

	private void writeBackUserInfo(YgUser receiveUser) {
		receiveUser.setUserType(UserType.UserAgent);
		ygUserService.updateUserType(UserType.UserAgent, receiveUser.getId());
	}

	/**
	 * 生成N个邀请码
	 * 
	 * @param user
	 */
	@Override
	public List<YgAgentInviteRecord> generateInviteCode(YgUser user, int count) {
		List<YgAgentInviteRecord> recordList = new ArrayList<>();
		if (!user.getUserType().equals(UserType.UserAgent)) {
			return recordList;
		}
		Date now = new Date();
		for (int i = 0; i < count; i++) { // 每月一个用户生成5个邀请码
			recordList.add(new YgAgentInviteRecord(user.getId(), user.getUserName(), now));
		}
		return recordList;
	}

	@Override
	public int generateInviteCodeToUser(Long userId) {
		YgUser user = ygUserService.findById(userId);
		if (!user.isUserAgent()) {
			return 0;
		}
		Date currentMonth = new Date();
		List<YgAgentInviteRecord> listByCurrentMonth = this.findByUserIdListAndBetweenTime(Arrays.asList(userId),
				DateConvertUtils.getMonthStartDate(currentMonth), DateConvertUtils.getDateEnd(DateConvertUtils.getMonthEndDate(currentMonth))); // 当月记录
		if (CollectionUtils.isNotEmpty(listByCurrentMonth)) { // 当月记录已经生成过
			return 0;
		}
		return generateInviteCodeToUser(user, currentMonth);
	}

	@Override
	public int generateInviteCodeToUser(YgUser user, Date currentMonth) {
		Date preMonth = DateConvertUtils.addMonth(currentMonth, -1);
		List<YgAgentInviteRecord> listByPreMonth = this.findByUserIdListAndBetweenTime(Arrays.asList(user.getId()),
				DateConvertUtils.getMonthStartDate(preMonth), DateConvertUtils.getDateEnd(DateConvertUtils.getMonthEndDate(preMonth))); // 上月记录
		int addCount = every_month_count;
		int row = 0;
		if (CollectionUtils.isNotEmpty(listByPreMonth)) {
			List<Long> unUsedList = listByPreMonth.stream().filter(o -> o.getReceiveUserId() == null).map(o -> o.getId()).collect(Collectors.toList());
			row += updateCreateTimeByIdList(unUsedList, currentMonth); // 修改上月记录，转成当月记录
			if (CollectionUtils.isNotEmpty(unUsedList)) {
				addCount = addCount - unUsedList.size();
			}
		}
		row += this.addBatch(generateInviteCode(user, addCount)); // 生成当月新邀请码
		return row;
	}

	private int updateCreateTimeByIdList(List<Long> idList, Date createTime) {
		if (CollectionUtils.isEmpty(idList)) {
			return 0;
		}
		return ygAgentInviteRecordMapper.updateCreateTimeByIdList(idList, createTime);
	}

	@Override
	public Message addCancelAgentJob(Long userId, String cancelBy) {
		YgAgentInviteRecord agentInviteRecord = this.findValidByReceiveUserId(userId);
		if (agentInviteRecord == null || agentInviteRecord.getCancelTime() != null) {
			return Message.success("当前用户不是代理用户", null);
		}
		Message message = scheduleJobService.addCancelAgentJob(agentInviteRecord.getId(), new Date(), cancelBy);
		if (message.getType().equals(Message.Type.success)) {
			this.update(new YgAgentInviteRecord(agentInviteRecord.getId(), null, null, null, null, CheckStatus.WaitingCancel, null));
		}
		return message;
	}

	@Override
	public void cancelAgent(Long id, String cancelBy) {
		YgAgentInviteRecord agentInviteRecord = this.findById(id);
		if (agentInviteRecord != null) {
			YgAgentInviteRecord update = new YgAgentInviteRecord();
			update.setId(id);
			update.setCancelBy(cancelBy);
			update.setCancelTime(new Date());
			update.setCheckStatus(CheckStatus.Cancel);
			if (this.update(update) > 0) {
				YgUser user = ygUserService.findById(agentInviteRecord.getReceiveUserId());
				ygUserService.updateAgentToCancelByUserId(user.getId());
				String url = "/discount/index.html?sCode=" + user.getUserName();
				wxMpMessageService.cancelAgentAuditMsg(user.getUserName(), user.getOpenId(),
						"您好，您的" + user.getUserType().getTitle() + "资格已被取消，有疑问请联系客服。", url);
			}
		}
	}

	@Override
	public Message rechargeUserAgentRightNow(Long userId, Boolean containOrdinaryUser) {
		YgUser user = ygUserService.findById(userId);
		if (user.isUserAgent()) {
			return Message.error("您当前已经是代理", null);
		}
		if (user.getLevel().compareTo(10) == 0) { // 女王转代理
			YgUserMember userMember = ygUserMemberService.findByUserId(user.getId());
			Date startTime = userMember.getMemberStartTime();
			Date expireTime = DateConvertUtils.getMonthEndDate(DateConvertUtils.addMonth(startTime, 12));
			return rechargeUserAgentBySelf(user, startTime, expireTime, InviteType.BuySelf);
		}
		YgAgent agent = ygAgentService.findByRecent(user.getId(), UserType.UserAgent);
		if (agent != null) {
			if (CheckStatus.Waiting.equals(agent.getCheckStatus())) { // 受邀请用户
				Date now = new Date();
				Date expireTime = DateConvertUtils.getMonthEndDate(DateConvertUtils.addMonth(now, 1));
				return rechargeUserAgentBySelf(user, now, expireTime, InviteType.Ordinary);
			} else if (Arrays.asList(CheckStatus.Pass, CheckStatus.WaitingCancel).indexOf(agent.getCheckStatus()) != -1) { // 老代理用户
				Date now = new Date();
				Date expireTime = DateConvertUtils.getMonthEndDate(DateConvertUtils.addMonth(now, 1));
				Date specificTime = DateConvertUtils.parse("2018-08-31 23:59:59", "yyyy-MM-dd HH:mm:ss");
				if (expireTime.before(specificTime)) {
					expireTime = specificTime;
				}
				Date startTime = agent.getCheckTime();
				return rechargeUserAgentBySelf(user, startTime, expireTime, InviteType.Ordinary);
			}
		}
		if (containOrdinaryUser != null && containOrdinaryUser) { // 普通用户直接转代理
			Date now = new Date();
			Date expireTime = DateConvertUtils.getMonthEndDate(DateConvertUtils.addMonth(now, 1));
			return rechargeUserAgentBySelf(user, now, expireTime, InviteType.Ordinary);
		}
		return Message.error("您当前无权立即成为新代理", null);
	}

	@Override
	public Message rechargeUserAgentBySelf(YgUser user, Date currentTime, Date expireTime, InviteType inviteType) {
		int row = this.saveAgentInviteRecordBySelf(user, currentTime, expireTime, inviteType);
		if (row > 0) {
			writeBackUserInfo(user); // 回写用户信息
			generateInviteCodeToUser(user, currentTime); // 成为代理，生成邀请码
			return Message.success(null);
		}
		return Message.error("请稍后重试", null);
	}

	private int saveAgentInviteRecordBySelf(YgUser user, Date currentTime, Date expireTime, InviteType inviteType) {
		YgAgentInviteRecord inviteRecord = new YgAgentInviteRecord();
		inviteRecord.setUserId(user.getId());
		inviteRecord.setUserName(user.getUserName());
		inviteRecord.setCreateTime(new Date());
		inviteRecord.setReceiveTime(currentTime);
		inviteRecord.setReceiveUserId(user.getId());
		inviteRecord.setReceiveUserName(user.getUserName());
		inviteRecord.setExpireTime(expireTime);
		inviteRecord.setInviteType(inviteType);
		inviteRecord.setCheckStatus(CheckStatus.Pass);
		int row = this.save(inviteRecord);
		if (row > 0) {
			writeBackUserInfo(user);
			updateBatchWithInviteCode(Arrays.asList(inviteRecord));
		}
		return row;
	}


	@Override
	public Message addPayRecordBySelf(Long userId, Date paidTime) {
		try {
			logger.info("{} 用户购买女王",userId);
			YgAgentInviteRecord agentInviteRecord = this.findValidByReceiveUserId(userId);
			logger.info("{} 用户购买女王, {}",userId,agentInviteRecord== null?"没有记录":JSON.toJSONString(agentInviteRecord));
			if (agentInviteRecord != null && agentInviteRecord.getCancelTime() == null
					&& agentInviteRecord.getExpireTime().getTime() > System.currentTimeMillis()) {
				logger.info("用户二次购买女王 ，userId: {},支付日期：{}",userId,DateConvertUtils.format(paidTime,DateConvertUtils.DATE_TIME_FORMAT));
				YgAgentInviteRecord update = new YgAgentInviteRecord();
				update.setId(agentInviteRecord.getId());
				update.setExpireTime(DateConvertUtils.addYear(agentInviteRecord.getExpireTime(), 1));
				this.update(update);
				
			}else{
				logger.info("{} 用户购买女王，新增一条记录",userId);
				YgUser user = ygUserService.findById(userId);
				Date expireTime = DateConvertUtils.getMonthEndDate(DateConvertUtils.addMonth(paidTime, 12));
				return rechargeUserAgentBySelf(user, paidTime, expireTime, InviteType.BuySelf);
			}
		} catch (Exception e) {
			logger.error("{} 用户购买女王 报错",e.getMessage());
			e.printStackTrace();
		}
		return Message.success(null);
	}

	@Override
	public Message applyToAgent(Long userId) {
		YgUserMember userMember = ygUserMemberService.findByUserId(userId);
		if(userMember != null && userMember.isMembersValid()){
			YgUser receiveUser = ygUserService.findById(userId);
			YgUser inviter = null;
			if(userMember.getInviterId().compareTo(userMember.getUserId()) != 0){
				inviter = ygUserService.findById(userMember.getInviterId());
			}
			this.doApplyToAgent(inviter, receiveUser, new Date(), userMember.getMemberEndTime(), InviteType.BuySelf);
		}else{
			return Message.error("您的女王会员已经过期，请先购买女王会员", userMember);
		}
		return Message.success(null);
	}

	@Override
	public Map<String, Object> findRecommendUserCount(Long userId, String platformNo) {
		YgUser user = ygUserService.findById(userId);
		if (UserType.UserAgent.equals(user.getUserType())) {
			return ygAgentInviteRecordMapper.selectRecommendUserCount(userId, null);
		}
		return ygAgentInviteRecordMapper.selectRecommendForRechargeUserAgent(userId, platformNo);
	}

	@Override
	public List<YgUserRecommendModel> findRecommendUser(QueryInfo queryInfo, YgUser user, String platformNo) {
		List<YgUserRecommendModel> list = selectRecommendUser(queryInfo, user, platformNo);
		if (CollectionUtils.isEmpty(list) || !UserType.UserAgent.equals(user.getUserType())) {
			return list;
		}
		List<Long> userIdList = list.stream().map(YgUserRecommendModel::getUserId).collect(Collectors.toList());
		List<YgUserRecommendModel> reportList = ygUserBalanceDetailService.
				statisticsRecommendPrice(user.getId(), userIdList, null);
		if (CollectionUtils.isEmpty(reportList)) {
			return list;
		}
		Map<Long, List<YgUserRecommendModel>> collect = reportList.stream()
				.collect(Collectors.groupingBy(YgUserRecommendModel::getUserId));
		list.forEach(o -> {
			if (collect.containsKey(o.getUserId())) {
				o.setDevoteIncomePrice(collect.get(o.getUserId()).get(0).getDevoteIncomePrice());
			}
		});
		return list;
	}

	private List<YgUserRecommendModel> selectRecommendUser(QueryInfo queryInfo, YgUser user, String platformNo) {
		if (UserType.UserAgent.equals(user.getUserType())) {
			return ygAgentInviteRecordMapper.selectRecommendUser(queryInfo, user.getId(), null);
		}
		return ygAgentInviteRecordMapper.selectRecommendUserBeforeRechargeUserAgent(queryInfo, user.getId(), platformNo);
	}

	private int doApplyToAgent(YgUser inviter,YgUser receiveUser, Date currentTime, Date expireTime, InviteType inviteType) {
		
		inviter= inviter==null?receiveUser:inviter;
		YgAgentInviteRecord inviteRecord = new YgAgentInviteRecord();
		inviteRecord.setUserId(inviter.getId());
		inviteRecord.setUserName(inviter.getUserName());
		inviteRecord.setCreateTime(new Date());
		inviteRecord.setReceiveTime(currentTime);
		inviteRecord.setReceiveUserId(receiveUser.getId());
		inviteRecord.setReceiveUserName(receiveUser.getUserName());
		inviteRecord.setExpireTime(expireTime);
		inviteRecord.setInviteType(inviteType);
		inviteRecord.setCheckStatus(CheckStatus.Pass);
		int row = this.save(inviteRecord);
		if (row > 0) {
			writeBackUserInfo(receiveUser);
		}
		return row;
	}

	@Override
	public YgAgentInviteRecord findRecordForYijiandian(Long receiveUserId) {
		YgAgentInviteRecord record = this.findValidByReceiveUserId(receiveUserId);
		if (record != null && record.getUserId().compareTo(record.getReceiveUserId()) == 0) {
			return null;
		}
		return record;
	}

	@Override
	public void processFromCodeByUserAgent(YgUser user, String fromCode) {
		if (StringUtils.isBlank(fromCode)) {
			return;
		}
		YgAgentInviteRecord record = this.findRecordForYijiandian(user.getId());
		if (record != null) {
			return;
		}
		YgUser fromUser = null;
		try {
			long id = ShareCodeUtil.codeToId(fromCode);
			fromUser = ygUserService.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (fromUser == null) {
			fromUser = ygUserService.findBySourceCode(fromCode);
		}
		bindShareUserAndFans(user, fromUser);
	}

	@Override
	public Message bindShareUserAndFans(YgUser currentUser, YgUser shareUser) {
		if (currentUser == null || shareUser == null) {
			return Message.error("用户信息异常", null);
		}
		YgAgentInviteRecord record = this.findRecordForYijiandian(currentUser.getId());
		if (record != null) {
			return Message.error("当前用户已绑定邀请用户", null);
		}
		if (currentUser.getId().compareTo(shareUser.getId()) == 0) {
			return Message.error("不能绑定自己", null);
		}
		record = this.findRecordForYijiandian(shareUser.getId());
		if (record != null && record.getUserId().compareTo(currentUser.getId()) == 0) {
			return Message.error("不可以绑定粉丝为邀请用户", null);
		}
		record = new YgAgentInviteRecord(null, currentUser.getId(), currentUser.getUserName(),
				new Date(), InviteType.Ordinary, CheckStatus.Pass, null);
		record.setUserId(shareUser.getId());
		record.setUserName(shareUser.getUserName());
		record.setCreateTime(new Date());
		record.setReceiveTime(record.getCreateTime());
		this.save(record);

		ygInformService.asyncSendInform(shareUser.getId(), currentUser.getNickName(),
				InformType.InviteSuccess, "inviteUser");
		return Message.success(null);
	}

	@Override
	public ResponseEntity validateUserForUserAgent(YgUser user, String platformNo, SalesPlatform salesPlatform) {
		Map<String, Object> dataMap = this.findRecommendUserCount(user.getId(), platformNo);
		Long totalUserCount = Long.valueOf(dataMap.get("totalUserCount").toString());
		String result = redisDao.get(String.format(RedisConstant.USER_AGENT_CONDITION_PREFIX_KEY, salesPlatform));
		Map mapFromRedis = JSON.parseObject(result, Map.class);
		Long limitUserCount = Long.valueOf(mapFromRedis.get("recommendCount").toString());
		if (limitUserCount.compareTo(totalUserCount) > 0) {
			return ResponseEntity.error("成为会员至少需要邀请" + limitUserCount + "个粉丝", null);
		}
		Long totalOrderCount = Long.valueOf(dataMap.get("totalOrderCount").toString());
		Long limitOrderCount = Long.valueOf(mapFromRedis.get("orderCount").toString());
		if (limitOrderCount.compareTo(totalOrderCount) > 0) {
			return ResponseEntity.error("成为会员至少需要" + limitOrderCount + "人成功下单", null);
		}
		return ResponseEntity.success();
	}

	@Override
	public ResultSet<YgUser> searchRecommendUser(QueryInfo queryInfo, Long userId) {
		Assert.notNull(userId);
		int total = ygAgentInviteRecordMapper.countRecommendUser(userId);
		if (total == 0) {
			return new ResultSet<>();
		}
		List<YgUser> result = ygAgentInviteRecordMapper.selectRecommendUserList(queryInfo, userId);
		return new ResultSet<>(total, result);
	}
}
